import { useReducer } from 'react';
import { usePersistFn } from 'ahooks';
import { Form } from 'antd';
import type { PovNumAndStatus, PovExtraAttribute } from '../utils/handlePovData';
import { getListPovConditionData } from '../utils/handlePovData';

export interface PovReducerType {
  initPovValue: Record<string, unknown>; // pov选项的默认值
  povHeightInfo: PovNumAndStatus; // pov是否是展开收缩,expand true 展开 false收缩
  povExtraParameters?: PovExtraAttribute; // pov的配置信息
  povIcon: boolean; // 标识pov数据切换后未进行刷新（是否显示刷新按钮上的小图标）
  pageLoading?: boolean;
}

export type PovActionType =
  | {
      type: 'init';
      initData: PovReducerType;
    }
  | {
      type: 'setInitPovValue';
      initPovValue: Record<string, unknown>;
    }
  | {
      type: 'setPovHeightInfo';
      povHeightInfo: PovNumAndStatus;
    }
  | {
      type: 'setPovIcon';
      povIcon: boolean;
    };

const povReducerTodo = (state: PovReducerType, action: PovActionType) => {
  switch (action.type) {
    case 'init': {
      return {
        ...state,
        ...action.initData,
      };
    }
    case 'setInitPovValue': {
      return {
        ...state,
        initPovValue: action.initPovValue,
      };
    }
    case 'setPovHeightInfo':
      return {
        ...state,
        povHeightInfo: action.povHeightInfo,
      };
    case 'setPovIcon':
      return {
        ...state,
        povIcon: action.povIcon,
      };
    default:
      return state;
  }
};

const initStateData = {
  initPovValue: {},
  povHeightInfo: {},
  povExtraParameters: {},
  povIcon: false,
  pageLoading: true,
};

const PovHook = () => {
  const [state, dispatch] = useReducer(povReducerTodo, initStateData as PovReducerType);
  // pov 区域form
  const [povForm] = Form.useForm();
  const { initPovValue, povExtraParameters = {} } = state;
  // 获取pov 数据
  const getPovData = usePersistFn(() => {
    return getListPovConditionData(povForm, povExtraParameters);
  });
  // pov值变更数据
  const onPovValuesChange = usePersistFn((changedValues: Record<string, any>) => {
    const [key] = Object.entries(changedValues)[0];
    const curInitPovValue = {
      ...initPovValue,
      ...changedValues,
    };
    if (changedValues[key] !== initPovValue[key]) {
      dispatch({
        type: 'setPovIcon',
        povIcon: true,
      });
    } else if (
      Object.keys(initPovValue).filter((k) => {
        return initPovValue[k] !== curInitPovValue[k];
      }).length === 0
    ) {
      dispatch({
        type: 'setPovIcon',
        povIcon: false,
      });
    }
  });

  return {
    state,
    dispatch,
    povForm,
    getPovData,
    onPovValuesChange,
  };
};

export default PovHook;
